<template>
  <div class="user-header">
    <el-button
      type="primary"
      v-if="permission.includes('role:add')"
      @click="handleAdd"
      >新增</el-button
    >
    <el-form :inline="true" :model="formInline">
      <el-form-item>
        <el-input v-model="formInline.name" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="formInline.date"
          @change="handleDateChange"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          date-format="YYYY-MM-DD ddd"
          time-format="A hh:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="table">
    <el-table
      :data="tableData"
      style="width: 100%; --el-table-border: 1px solid #d6d9e1"
    >
      <el-table-column prop="id" label="ID" width="200" />
      <el-table-column
        prop="role_name"
        label="角色名称"
        width="200"
        show-overflow-tooltip
      />
      <el-table-column prop="create_time" label="报名时间" width="200" />
      <el-table-column prop="update_time" label="更新时间" width="200" />
      <!-- 操作列 -->
      <el-table-column
        fixed="right"
        label="操作"
        min-width="290"
        align="center"
      >
        <template #="scope">
          <el-button
            type="primary"
            :disabled="scope.row.id == 1"
            size="small"
            v-if="permission.includes('role:update')"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            :disabled="scope.row.id == 1"
            size="small"
            v-if="permission.includes('role:delete')"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
            type="warning"
            :disabled="scope.row.id == 1"
            size="small"
            v-if="permission.includes('role:menu')"
            @click="showAssignMenu(scope.row)"
          >
            分配菜单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="pager"
      :page-size="config.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="config.total"
      @size-change="handleSizeChange"
      @current-change="handleChange"
    />
  </div>

  <!-- 新增弹出框内容 -->
  <el-dialog
    v-model="dialogVisible"
    :title="action == 'add' ? '新增' : '编辑'"
    :rules="rules"
    width="800px"
  >
    <el-form label-width="200" :model="formData" ref="dataForm">
      <el-form-item v-if="false" prop="id">
        <el-input v-model="formData.id" />
      </el-form-item>
      <el-form-item label="角色" prop="role_name">
        <el-input v-model="formData.role_name" placeholder="请输入角色" />
      </el-form-item>

      <el-form-item label="权限字符" prop="role_key">
        <el-input v-model="formData.role_key" placeholder="请输入权限字符" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 分配菜单对话框 -->
  <!-- 分配菜单对话框 -->
  <el-dialog v-model="dialogMenuVisible" title="分配菜单" width="40%">
    <!-- 红色提示文字，标题下方 -->
    <div style="color: #f56c6c; font-size: 12px; margin-bottom: 10px">
      （如果有子菜单，父菜单会自动补全）
    </div>

    <el-form label-width="80px">
      <el-tree
        :data="sysMenuTreeList"
        ref="tree"
        show-checkbox
        default-expand-all
        :default-checked-keys="defaultTreeArray"
        node-key="id"
        :check-on-click-node="true"
        :check-strictly="true"
      />
      <el-form-item>
        <el-button type="primary" @click="submitAssignMenu">提交</el-button>
        <el-button @click="dialogMenuVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {
  ref,
  getCurrentInstance,
  onMounted,
  reactive,
  nextTick,
  watch,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  RoleList,
  assignMenu,
  djSelect,
  getRoleMenu,
  addRole,
  updateRole,
  RoleDelete,
} from "@/api/index.js";
import { useAllDataStore } from "@/stores";
let defaultTreeArray = ref([]);
// 状态控制
const sysMenuTreeList = ref([]);
const tree = ref(null);
const roleId = ref(); // 当前操作的角色ID

// 菜单树配置
const defaultProps = {
  children: "children",
  label: "label",
};
const dialogMenuVisible = ref(false);
//新增或编辑的弹窗
const dialogVisible = ref(false); // 假设你有一个 dialogVisible 变量
const action = ref("add"); // 假设你有一个 action 变量
const imageUrl = ref("");
let allDataStore = useAllDataStore();
let permission = allDataStore.state.permissionList;

watch(dialogVisible, (newValue) => {
  if (!newValue) {
    imageUrl.value = ""; // 只重置 imageUrl ✅
  }
});

//表单校验规则
const rules = reactive({
  role_name: [{ required: true, message: "角色名称是必填项", trigger: "blur" }],
  role_key: [{ required: true, message: "权限字符是必填项", trigger: "blur" }],
});

const dataForm = ref(null);
const formData = reactive({
  id: "",
  role_name: "",
  role_key: "",
});

const handleReset = () => {
  formInline.name = "";
  formInline.beginTime = "";
  formInline.endTime = "";
  config.role_name = "";
  config.beginTime = "";
  config.endTime = "";
  getData();
};

////弹窗关闭
const handleCancel = () => {
  dataForm.value.resetFields();
  dialogVisible.value = false;
  imageUrl.value = ""; // 关闭弹窗时清除预览
};

//新增窗口
const handleAdd = () => {
  dialogVisible.value = true;
  action.value = "add";
};

// const onSubmit = async () => {
//   if (action.value === "add") {
//     addUser(formData).then((data) => {
//       if (data.data.code === 200) {
//         ElMessage.success("成功");
//         handleCancel();
//         getData();
//       } else {
//         ElMessage.error(data.data.msg);
//       }
//     });
//   } else if (action.value === "edit") {
//     updateUser(formData).then((data) => {
//       if (data.data.code === 200) {
//         ElMessage.success("成功");
//         handleCancel();
//         getData();
//       } else {
//         ElMessage.error(data.data.msg);
//       }
//     });
//   } else {
//     ElMessage.error("操作失败");
//   }
// };
const onSubmit = () => {
  dataForm.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error("请完善表单信息");
      return;
    }

    try {
      let res;
      if (action.value === "add") {
        // 新增时清理id
        const submitData = { ...formData };
        delete submitData.id; // 删除id字段，避免传空字符串

        res = await addRole(submitData);
      } else if (action.value === "edit") {
        res = await updateRole(formData);
      } else {
        ElMessage.error("未知操作");
        return;
      }

      if (res.data.code === 200) {
        ElMessage.success("操作成功");
        handleCancel();
        getData();
      } else {
        ElMessage.error(res.data.msg || "操作失败");
      }
    } catch (error) {
      ElMessage.error("请求失败，请稍后重试");
      console.error(error);
    }
  });
};

const formInline = reactive({
  name: "",
  beginTime: "",
  endTime: "",
});

const config = reactive({
  role_name: "",
  beginTime: "",
  endTime: "",
  total: 0,
  page: 1,
  pageSize: 10,
});

const handleSearch = () => {
  config.role_name = formInline.name;
  config.beginTime = formInline.beginTime;
  config.endTime = formInline.endTime;
  config.page = 1; // 重置为第一页
  getData();
};

const tableData = ref([]);

const getData = async () => {
  try {
    const { data } = await RoleList(config);
    // console.log(data.data.data);

    tableData.value = data.data.data;
    // tableData.value = data.data.data.sort((a, b) => {
    //   return a.id - b.id;
    // });
    config.total = data.data.total;
  } catch (error) {
    console.error("获取数据失败", error);
  }
};

const handleChange = (page) => {
  config.page = page;
  getData();
};

const handleSizeChange = (size) => {
  config.pageSize = size;
  getData();
};

// 删除方法
const handleDelete = async (val) => {
  try {
    await ElMessageBox.confirm("确定删除该用户吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await RoleDelete({ ids: [val.id] });

    // ⚠️ 根据你后端返回结构调整这里
    const data = response.data || response;

    // console.log("返回结果：", data);

    if (data.code === 200) {
      ElMessage({
        showClose: true,
        type: "success",
        message: "删除成功",
      });
      getData(); // ✅ 刷新表格数据
    } else {
      ElMessage.error(data.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败，请查看控制台");
      console.error("删除失败：", error);
    }
  }
};
// 日期选择器
let handleDateChange = (e) => {
  formInline.beginTime = new Date(e[0]).toLocaleString();
  formInline.endTime = new Date(e[1]).toLocaleString();
};
// 修改方法
const handleEdit = (val) => {
  action.value = "edit";
  dialogVisible.value = true;
  nextTick(() => {
    Object.assign(formData, { ...val });
  });
};

// 转成树id（先序遍历，先取当前节点id，再取子节点）
let getTreeId = (data = [], result = []) => {
  data.forEach((item) => {
    result.push(+item.id); // 先加入当前节点id
    if (item.children && item.children.length > 0) {
      getTreeId(item.children, result);
    }
  });
  return result;
};

// 📌 分配菜单弹窗
const showAssignMenu = async (row) => {
  defaultTreeArray.value = [];
  dialogMenuVisible.value = true;
  roleId.value = row.id;
  try {
    // 获取角色已拥有的菜单
    const idsRes = await getRoleMenu({ role_id: row.id });
    // 获取所有菜单
    const res = await djSelect();
    const menuTree = res.data.data.data || [];
    const roleMenuTree = idsRes.data.data || [];

    sysMenuTreeList.value = menuTree;

    // 扁平化所有已拥有菜单id
    const checkedKeys = getTreeId(roleMenuTree);

    // 赋值给回显选中数组
    defaultTreeArray.value = checkedKeys;

    await nextTick();

    // 设置树选中节点
    // console.log("角色已拥有的菜单", checkedKeys);
    tree.value.setCheckedKeys(checkedKeys, false);
  } catch (error) {
    ElMessage.error("菜单获取失败！");
    console.error("菜单数据错误：", error);
  }
};

// 📌 提交菜单分配
const submitAssignMenu = async () => {
  const checkedKeys = tree.value.getCheckedKeys();
  try {
    const res = await assignMenu({
      role_id: roleId.value,
      menu_ids: checkedKeys, // ✅ 根据你提供的字段要求
    });

    if (res.data.code === 200) {
      ElMessage.success("菜单分配成功！");
      dialogMenuVisible.value = false;
    } else {
      ElMessage.error(res.data.msg || "菜单分配失败！");
    }
  } catch (error) {
    ElMessage.error("请求失败，请查看控制台！");
    console.error("assignMenu error:", error);
  }
};

onMounted(() => {
  getData();
});
</script>
<style scoped lang="less">
.user-header {
  display: flex;
  justify-content: space-between;
}

.table {
  position: relative;
  // height: 520px;
  background-color: #fff;

  .pager {
    // position: absolute;
  }

  .el-table {
    // height: 500px;
    width: 100%;
  }
}

:deep(.el-form-item__content) {
  justify-content: center;
}

:deep(.el-form-item__label) {
  height: auto;
}

.avatar {
  width: 100px;
  height: 100px;
}
</style>
